<template>
  <div class="dish-edit-container">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
      <!-- 菜品名称 -->
      <div class="form-section">
        <el-form-item label="菜品名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入菜品名称" clearable />
        </el-form-item>

        <!--菜品分类-->
        <el-form-item label="菜品分类" prop="categoryId">
          <el-select v-model="form.categoryId" placeholder="请选择分类" clearable>
            <el-option
                v-for="category in dishCategories"
                :key="category.id"
                :label="category.name"
                :value="category.id"
            />
          </el-select>
        </el-form-item>

        <!--菜品价格-->
        <el-form-item label="菜品价格" prop="price">
          <el-input-number
              v-model="form.price"
              :min="0"
              :max="9999"
              :precision="2"
              controls-position="right"
          />
          <span class="unit">元</span>
        </el-form-item>
      </div>

      <!-- 分隔线 -->
      <el-divider />

      <!-- 口味信息 -->
      <el-form-item label="已选口味" prop="flavors">
        <div v-if="form.flavors.length > 0">
          <el-tag
              v-for="(flavor, index) in form.flavors"
              :key="index"
              closable
              @close="removeFlavor(index)"
          >
            {{ flavor.attribute }}: {{ flavor.value }}
          </el-tag>
        </div>
        <el-button
            type="primary"
            plain
            @click="openFlavorDialog"
        >
          添加口味
        </el-button>
        <span v-if="form.flavors.length === 0" class="el-form-item__error">
      请至少选择一种口味
    </span>
      </el-form-item>

      <!-- 分隔线 -->
      <el-divider />

      <!-- 菜品图片 -->
      <el-form-item label="菜品图片" prop="image">
        <el-upload
            class="image-uploader"
            :show-file-list="false"
            :before-upload="beforeImageUpload"
            :http-request="customUpload"
            accept="image/*"
        >
          <div class="image-preview">
            <!-- 加载状态 -->
            <div v-if="uploadLoading" class="upload-mask">
              <el-icon class="is-loading"><Loading /></el-icon>
              <span class="ml-2">上传中...</span>
            </div>

            <!-- 预览显示 -->
            <img v-if="form.imagePreview" :src="form.imagePreview" class="dish-image" />
            <el-icon v-else class="uploader-icon"><Plus /></el-icon>
          </div>
        </el-upload>
      </el-form-item>

      <!-- 分隔线 -->
      <el-divider />

      <!-- 菜品描述 -->
      <div class="form-section">
        <el-form-item label="菜品描述" prop="description">
          <el-input
              v-model="form.description"
              type="textarea"
              :rows="3"
              placeholder="请输入菜品描述(0-300字)"
              maxlength="300"
              show-word-limit
          />
        </el-form-item>
      </div>

      <!-- 操作按钮 -->
      <div class="action-buttons">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="submitForm">保存</el-button>
      </div>
    </el-form>

    <!-- 口味选择对话框 -->
    <el-dialog v-model="flavorDialogVisible" title="选择口味" width="600px">
      <div class="flavor-dialog-content">
        <div class="flavor-options">
          <el-tabs v-model="activeFlavorTab">

            <el-tab-pane label="辣度" name="spicy">
              <el-checkbox-group v-model="selectedFlavor.values.spicy">
                <el-checkbox label="不辣" />
                <el-checkbox label="微辣" />
                <el-checkbox label="中辣" />
                <el-checkbox label="重辣" />
              </el-checkbox-group>
            </el-tab-pane>

            <el-tab-pane label="忌口" name="taboo">
              <el-checkbox-group v-model="selectedFlavor.values.taboo">
                <el-checkbox label="不要葱" />
                <el-checkbox label="不要蒜" />
                <el-checkbox label="不要香菜" />
                <el-checkbox label="不要辣" />
              </el-checkbox-group>
            </el-tab-pane>

            <el-tab-pane label="甜度" name="sweetness">
              <el-checkbox-group v-model="selectedFlavor.values.sweetness">
                <el-checkbox label="无糖" />
                <el-checkbox label="微糖" />
                <el-checkbox label="半糖" />
                <el-checkbox label="全糖" />
              </el-checkbox-group>
            </el-tab-pane>

            <el-tab-pane label="温度" name="temperature">
              <el-checkbox-group v-model="selectedFlavor.values.temperature">
                <el-checkbox label="常温" />
                <el-checkbox label="加热" />
                <el-checkbox label="加冰" />
                <el-checkbox label="去冰" />
              </el-checkbox-group>
            </el-tab-pane>

            <el-tab-pane label="规格" name="specification">
              <el-checkbox-group v-model="selectedFlavor.values.specification">
                <el-checkbox label="小份" />
                <el-checkbox label="标准" />
                <el-checkbox label="大份" />
              </el-checkbox-group>
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>

      <template #footer>
        <el-button @click="flavorDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="addFlavor">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, onMounted, watch, reactive} from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import {getCategoryByType} from "@/api/category";
import {fileViewPath, uploadFile} from "@/utils/file";
import {getDishById, saveDishAndFlavor, updateDishAndFlavor} from "@/api/dish";

const route = useRoute()
const router = useRouter()
const isEditMode = ref(route.name === 'editDish')
const formRef = ref(null)

// 表单数据
const form = reactive({
      id: null,
      name: '',
      categoryId: null,
      price: 0,
      image: '',
      imagePreview: '',//前端展示图谱的完整url
      description: '',
      flavors: []
})
// 验证规则
const rules = {
  name: [
    { required: true, message: '请输入菜品名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在2到50个字符', trigger: 'blur' }
  ],
  categoryId: [
    { required: true, message: '请选择菜品分类', trigger: 'change' }
  ],
  price: [
    { required: true, message: '请输入菜品价格', trigger: 'blur' },
    { type: 'number', min: 0, message: '价格不能为负数', trigger: 'blur' }
  ],
  image: [
    { required: true, message: '请上传菜品图片', trigger: 'change' }
  ],
  flavors: [
    {
      validator: (rule, value, callback) => {
        if (!value || value.length === 0) {
          callback(new Error('请至少选择一种口味'))
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ]
}

// 菜品分类数据
const dishCategories = ref([])
// 加载菜品分类
const loadDishCategories = async () => {
  try {
    const res = await getCategoryByType(1)
    if (res.code === '200') {
      dishCategories.value = res.data
    }else{
      ElMessage.error('获取分类失败')
    }
  } catch (error) {
    ElMessage.error('获取分类失败')
  }
}

// 如果是编辑模式，加载菜品数据
const loadDishData = async () => {
  if (!isEditMode.value) return

  const res = await getDishById(route.params.id);
  if(res.code === '200'){
    // 转换口味数据格式
    const flavors = res.data.flavors?.map(item => ({
      attribute: item.name || getFlavorType(item.value), // 添加类型判断
      value: item.value
    })) || [];
    Object.assign(form,{//响应式更新
      ...res.data,
      flavors, // 将转换后的口味数据赋值给表单
      imagePreview: `${fileViewPath}${formatImagePath(res.data.image)}`
    })
  }else{
    ElMessage.error('获取菜品信息失败!')
  }
}


/*口味选择对话框*/
const flavorDialogVisible = ref(false)
const activeFlavorTab = ref('spicy')

const selectedFlavor = ref({
  activeType: 'spicy',

  //各种类型的独立存储
  values: {
    spicy: [], //辣度（单选）
    taboo: [], //忌口（多选）
    sweetness: [], //甜度（单选）
    temperature: [], //温度（单选）
    specification: [] //规格（单选）
  }
})

//打开口味选择对话框
const openFlavorDialog = () => {
  selectedFlavor.value = {
    activeType: activeFlavorTab.value,
    values: {
      spicy: [],
      taboo: [],
      sweetness: [],
      temperature: [],
      specification: []
    }
  }
  flavorDialogVisible.value = true
}
//映射对应的中文名
const getTabName = (tab) => {
  const map = {
    spicy: '辣度',
    taboo: '忌口',
    sweetness: '甜度',
    temperature: '温度',
    specification: '规格'
  }
  return map[tab] || tab
}

const addFlavor = () => {
  if (!selectedFlavor.value?.values) {
    console.error('Flavor values not initialized')
    return
  }

  const type = activeFlavorTab.value
  const values = selectedFlavor.value.values

  try {
    // 统一处理所有多选类型
    if (!Array.isArray(values[type])) {
      values[type] = []
    }

    if (values[type].length === 0) {
      ElMessage.warning(`请至少选择一个${getTabName(type)}选项`)
      return
    }

    // 确保使用正确的属性名
    const attributeName = getTabName(type)
    const valueToAdd = values[type].join(',')

    // 检查是否已存在相同属性
    const exists = form.flavors.some(
        f => f.attribute === attributeName &&
            f.value === valueToAdd
    )

    if (!exists) {
      form.flavors.push({
        attribute: attributeName,  // 确保使用标准属性名
        value: valueToAdd
      })
      ElMessage.success('口味添加成功')
    } else {
      ElMessage.warning('该口味组合已存在')
    }

    flavorDialogVisible.value = false
  } catch (error) {
    console.error('添加口味失败:', error)
    ElMessage.error('操作失败，请重试')
  }
}

const removeFlavor = (index) => {
  form.flavors.splice(index, 1)
}


/*文件上传*/
// 上传加载状态
const uploadLoading = ref(false)
// 路径格式化函数（处理Windows路径）
const formatImagePath = (path) => {
  if (!path) return '';
  return path.replace(/\\/g, '/'); // 将反斜杠替换为斜杠
};

// 自定义上传方法
const customUpload = async (options) => {
  try {
    uploadLoading.value = true

    // 创建 FormData
    const formData = new FormData()
    formData.append('file', options.file) // 后端接受文件的字段名

    // 调用上传接口
    const res = await uploadFile({
      url: '/file/upload',
      data: formData
    })

    const {code,data,msg} = res.data;
    // 处理响应（根据实际接口结构调整）
    if (code === '200') {
      form.image = formatImagePath(data)
      form.imagePreview = `${fileViewPath}${formatImagePath(data)}`
      ElMessage.success('图片上传成功')
      return data;//返回上传成功
    } else {
      ElMessage.error(msg || '上传失败')
      return Promise.reject(msg)
    }
  } catch (error) {

    let errorMsg = '上传失败';
    if (error.response) {
      errorMsg = `服务器错误: ${error.response.status}`;
    } else if (error.message.includes('timeout')) {
      errorMsg = '请求超时，请重试';
    } else if (error.message) {
      errorMsg = error.message;
    }

    ElMessage.error(errorMsg);
    throw error; // 继续抛出错误供外部处理
  } finally {
    uploadLoading.value = false
  }
}
// 上传前校验
const beforeImageUpload = (file) => {
  // 文件类型验证
  const validTypes = ['image/jpeg', 'image/png', 'image/gif']
  const isImage = validTypes.includes(file.type)

  // 文件大小验证（2MB）
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('仅支持 JPG/PNG/GIF 格式!')
    return false
  }

  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }

  // 添加图片预览（可选）
  const reader = new FileReader()
  reader.onload = (e) => {
    // 临时显示本地预览
    form.image = e.target.result
  }
  reader.readAsDataURL(file)

  return true
}


// 表单提交
const submitForm = async () => {
  try {
    await formRef.value.validate()

    const submitFormData = {
      ...form,
      image: form.image,
      flavors: form.flavors.map(flavor =>({
        name: flavor.attribute,
        value: flavor.value
      }))
    }

    const res = isEditMode.value
                ? await updateDishAndFlavor(submitFormData)
                :await saveDishAndFlavor(submitFormData)

    if(res.code === '200'){
      ElMessage.success({
        message: isEditMode.value ? res.data ||'修改成功' : res.data || '添加成功',
        duration: 2000
      })
      router.back();
    }else{
      ElMessage.error(res.msg || '操作失败');
    }
  } catch (error) {
    console.error('操作失败:', error)
    // 更精细的错误处理
    if (error.response) {
      const msg = error.response.data?.msg ||
          error.response.data?.message ||
          '请求处理失败'
      ElMessage.error(`操作失败: ${msg}`)
    } else {
      ElMessage.error('网络或系统错误')
    }
  }
}

// 取消
const handleCancel = () => {
  router.back()
}

// 初始化
onMounted(async () => {
  await loadDishCategories()
  await loadDishData()
})
</script>

<style scoped>
.dish-edit-container {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.form-section {
  margin-bottom: 20px;
}

.image-uploader {
  width: 200px;
  height: 200px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
}

.dish-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.uploader-icon {
  font-size: 28px;
  color: #8c939d;
}

/* 添加固定尺寸和预览样式 */
.image-preview {
  width: 200px;
  height: 200px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
}

.dish-image {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}

.unit {
  margin-left: 10px;
  color: #666;
}

.unit {
  margin-left: 10px;
  color: var(--el-text-color-secondary);
  font-size: 14px;
}

.flavor-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  align-items: center;
}

.dish-image {
  width: 200px;
  height: 150px;
  display: block;
  cursor: pointer;
  border-radius: 4px;
  border: 1px solid var(--el-border-color);
}

.action-buttons {
  display: flex;
  justify-content: center;
  margin-top: 30px;
  gap: 20px;
}

.el-checkbox {
  display: block;
  margin: 8px 0;
}
/* 调整分隔线样式 */
.el-divider {
  margin: 20px 0;
}

/* 紧凑布局调整 */
.el-form-item {
  margin-bottom: 18px;
}
</style>